/**
 * @description 基于proxy，监听对象的中的属性的删除，Object.defineProperty() 是做不到的
 */

let observerMap = new Map();


function makeObserver(target) {
    let handlerName = Symbol('handler');
    observerMap.set(handlerName, [])


    target.observer = function (fn) {
        console.log(fn);
        observerMap.get(handlerName).push(fn)
    }

    const proxyHandler = {
        get: function (obj, prop) {
            if (typeof obj[prop] === 'object' && obj[prop] !== null) {
                return new Proxy(obj[prop], proxyHandler)
            }
            let success = Reflect.get(...arguments)
            if (success) {
                observerMap.get(handlerName)
                observerMap.get(handlerName).forEach(handler => handler('GET', prop, obj[prop]))
            }
            return success
        },
        set: function (obj, prop, val) {
            let success = Reflect.set(...arguments)
            if (success) {
                observerMap.get(handlerName).forEach(handler => handler('SET', prop, val))
            }
            return success
        },
        deleteProperty: function (obj, prop) {
            let success = Reflect.deleteProperty(...arguments)
            if (success) {
                observerMap.get(handlerName).forEach(handler => handler('DELETE',))
            }
            return success
        }
    }

    return new Proxy(target, proxyHandler)
}

let user = {}

user = makeObserver(user)
console.log(user);

user.observer = ((action, key, value) => {
    console.log(`${action} key=${key} value=${value || ''}`);
})


user.name = 'wb' // SET key=name value ='wb'
console.log(user.name); // GET key=name value='wb'
delete user.name // DELETE key=name value ='' // 最主要的是这里，需要坚挺删除操作
